package io.renren.modules.substation.service.impl;

import io.renren.modules.substation.dao.TBusiDevStatusInfoDao;
import io.renren.modules.substation.entity.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.Query;

import io.renren.modules.substation.dao.TInfoAlarmConfigDao;
import io.renren.modules.substation.service.TInfoAlarmConfigService;


@Service("tInfoAlarmConfigService")
public class TInfoAlarmConfigServiceImpl extends ServiceImpl<TInfoAlarmConfigDao, TInfoAlarmConfigEntity> implements TInfoAlarmConfigService {

    @Autowired
    private TBusiDevStatusInfoServiceImpl tBusiDevStatusInfoServiceImpl;
    @Autowired
    private TBaseDictInfoServiceImpl tBaseDictInfoServiceImpl;

    private static boolean cacheAlarmConfigFlag = false;
    private static Map<String, TInfoAlarmConfigEntity> SysCacheAlarmConfigMap;

    private static boolean cacheDevHealthFlag = false;
    private static Map<String, String> SysCacheDevHealthFlagMap;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {

        String devCode = (String)params.get("devCode");

        IPage<TInfoAlarmConfigEntity> page = this.page(
                new Query<TInfoAlarmConfigEntity>().getPage(params),
                new QueryWrapper<TInfoAlarmConfigEntity>()
                        .eq(devCode!=null&&!devCode.isEmpty(),"dev_code",devCode)
        );

        return new PageUtils(page);
    }

    /**
     * 获取全局缓存-告警阈值配置信息
     */
    @Override
    public Map<String, TInfoAlarmConfigEntity> getCacheAlarmConfigMap() {
        if (!cacheAlarmConfigFlag) {
            Map<String, TInfoAlarmConfigEntity> map = new HashMap<>();
            List<TInfoAlarmConfigEntity> list = baseMapper.selectList(new QueryWrapper<TInfoAlarmConfigEntity>());
            for (TInfoAlarmConfigEntity obj : list) {
                String key = obj.getDevCode() + "-";
                key += getVariableNameDesc(obj.getVariableName());
                if (!map.containsKey(key))
                    map.put(key, obj);
            }
            SysCacheAlarmConfigMap = map;
            cacheAlarmConfigFlag = true;
        }
        return SysCacheAlarmConfigMap;
    }

    private String getVariableNameDesc(String name){
        String desc = "";
        if (name.contains("环境量"))
            desc += "0" + name.substring(3, 4) + name.substring(5, 7);
        else  if (name.contains(ConstChinese.CH_JF))
            desc += "00" + name;
        else
            desc += "00" + name;
        return desc;
    }

    /**
     * 获取指定key(设备+变量)对应的告警阈值配置信息
     */
    @Override
    public TInfoAlarmConfigEntity getCacheAlarmConfigInfo(String key) {
        if (!cacheAlarmConfigFlag) {
            refreshCacheAlarmConfig();
        }
        return SysCacheAlarmConfigMap.get(key);
    }

    /**
     * 比较局放、哄红外告警值
     * key=variableId+variableKind
     * type:1-频次;2-峰值;3-均值
     * return:0-正常;1-告警
     */
    @Override
    public String compareVariableAlarmConfig(String devCode, String key, String type, String variableValue) {
        if (!cacheAlarmConfigFlag) {
            refreshCacheAlarmConfig();
        }
        TInfoAlarmConfigEntity info = new TInfoAlarmConfigEntity();
        if (key.equals("700") && type.equals("1")) {//局放频次
            info = SysCacheAlarmConfigMap.get(devCode + "-00局放频次");
        }else if (key.equals("700") && type.equals("2")) {//局放峰值
            info = SysCacheAlarmConfigMap.get(devCode + "-00局放峰值");
        }else if (key.equals("700") && type.equals("3")) {//局放均值
            info = SysCacheAlarmConfigMap.get(devCode + "-00局放均值");
        }else if (key.equals("800") && type.equals("1")) {//红外最高温
            info = SysCacheAlarmConfigMap.get(devCode + "-00红外最高温");
        }else if (key.equals("800") && type.equals("2")) {//红外最低温
            info = SysCacheAlarmConfigMap.get(devCode + "-00红外最低温");
        }
        if (info != null && (info.getVariableMax().compareTo(variableValue) < 0 || info.getVariableMin().compareTo(variableValue) > 0))
            return "1";
        else
            return "0";
    }

    /**
     * 更新全局缓存-告警阈值配置信息
     */
    @Override
    public void refreshCacheAlarmConfig() {
        Map<String, TInfoAlarmConfigEntity> map = new HashMap<>();
        List<TInfoAlarmConfigEntity> list = baseMapper.selectList(new QueryWrapper<TInfoAlarmConfigEntity>());
        for (TInfoAlarmConfigEntity obj : list) {
            String _key = obj.getDevCode() + "-";
            _key += getVariableNameDesc(obj.getVariableName());
            if (!map.containsKey(_key))
                map.put(_key, obj);
        }
        SysCacheAlarmConfigMap = map;
        cacheAlarmConfigFlag = true;
    }

    @Override
    public int updateHealthStatus(String key, String status) {
        String[] keys = key.split("-");
        if (keys.length < 2)
            return -1;
        if (keys[1].length() < 2)
            return -1;
        String devCode = keys[0];
        String name = getVariableDescName(keys[1]);
        TInfoAlarmConfigEntity tInfoAlarmConfigEntity = new TInfoAlarmConfigEntity();
        tInfoAlarmConfigEntity.setDevCode(devCode);
        tInfoAlarmConfigEntity.setVariableName(name);
        tInfoAlarmConfigEntity.setHealthStatus(status);
        tInfoAlarmConfigEntity.setLastOpr((long)0);
        tInfoAlarmConfigEntity.setLastTime(new Date());
        return baseMapper.updateHealthStatus(tInfoAlarmConfigEntity);
    }

    private String getVariableDescName(String desc){
        String name = "";
        String kind = desc.substring(0, 2);
        if ("00".equals(kind))
            name += desc.substring(2, desc.length());
        else
            name += "环境量" + desc.substring(1, 2) + "-" + desc.substring(2, desc.length());
        return name;
    }

    /**
     * 定时任务：
     * 1、刷新设备健康状态(通过alarmConfig表的healthStatus值判定)
     * 2、刷新设备在线状态(通过status表的lastTime值判定)
     */
    @Override
    public void jobRefreshDevHealth() {
        // 1、刷新设备健康状态(通过alarmConfig表的healthStatus值判定)
        List<TInfoAlarmConfigEntity> list = baseMapper.getDevHealthStatusGroup();
        TBusiDevStatusInfoEntity tBusiDevStatusInfoEntity;
        for (TInfoAlarmConfigEntity o : list) {
            tBusiDevStatusInfoEntity = new TBusiDevStatusInfoEntity();
            tBusiDevStatusInfoEntity.setDevCode(o.getDevCode());
            tBusiDevStatusInfoEntity.setIsAlarm(o.getCountNum() > 0 ? "1" : "0");
            //定时任务不能更新lastTime，否则会影响设备离线状态时间的判定
//            tBusiDevStatusInfoEntity.setLastOpr((long)0);
//            tBusiDevStatusInfoEntity.setLastTime(new Date());
            tBusiDevStatusInfoServiceImpl.updateDevStatusInfoByCode(tBusiDevStatusInfoEntity);
        }
        //2、刷新设备在线状态(通过status表的lastTime值判定)
        String s_timeSpan = "300";//300s
        TBaseDictInfoEntity dict = tBaseDictInfoServiceImpl.getCacheDictInfoByKey("DEV_OFFLINE_TIMESPAN");
        if (dict != null)
            s_timeSpan = dict.getDictValue();
        long l_timeSpan = Long.parseLong(s_timeSpan)*1000;
        List<TBusiDevStatusInfoEntity> devList = tBusiDevStatusInfoServiceImpl.list();
        for (TBusiDevStatusInfoEntity o : devList) {
            Date d_lastTime = o.getLastTime() == null ? o.getCreateTime() : o.getLastTime();
            Date d_nowTime = new Date();
            if (o.getDevStatus().equals("0") && (d_lastTime.getTime() + l_timeSpan > d_nowTime.getTime())){
                o.setDevStatus("1");//在线
                tBusiDevStatusInfoServiceImpl.updateDevStatusInfoByCode(o);
            }else if (o.getDevStatus().equals("1") && (d_lastTime.getTime() + l_timeSpan <= d_nowTime.getTime())){
                o.setDevStatus("0");//离线
                tBusiDevStatusInfoServiceImpl.updateDevStatusInfoByCode(o);
            }

        }
    }

}